import {
  getPurchaseOrderByPage,
  addPurchaseOrderDetail,
  exportPurchaseOrder,
  getPurchaseOrderTotalByPage,
  purchaseOrderInfoSync,
} from '@/services/product/purchaseOrder';
import { Ellipsis } from '@/components/Ellipsis';
import './product.module.less';
import { PlusOutlined, RedoOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Col, Row } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useRef, useState } from 'react';
import PurchaseOrderDetail from './purchaseOrderDetail';
import { tableSearchPublicConfig } from '@/utils/filterUtils';

const PurchaseOrder: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [detailVisit, setDetailVisit] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新增物料'); //
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [poIdentification, setPoIdentification] = useState();
  const [purchaseOrderId, setPurchaseOrderId] = useState<string>();
  const detailRef = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 60,
    },
    {
      title: '项目名称',
      align: 'center',
      sorter: true,
      dataIndex: 'projectName',
      width: 200,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目交货日期',
      align: 'center',
      sorter: true,
      dataIndex: 'sendDate',
      search: false,
    },
    {
      title: '采购订单号',
      align: 'center',
      sorter: true,
      dataIndex: 'po',

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '采购订单行',
      align: 'center',
      sorter: true,
      dataIndex: 'poItem',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '物料编号',
      align: 'center',
      sorter: true,
      dataIndex: 'materialCode',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      align: 'center',
      sorter: true,
      width: 150,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '采购预警',
      align: 'center',
      sorter: true,
      dataIndex: 'purchaseAlerts',
      search: false,

      render: (text) => {
        let color = 'red-retangle base-retangle';
        if (text === 'y') {
          color = 'yellow-retangle base-retangle';
        } else if (text === 'g') {
          color = 'green-retangle base-retangle';
        }
        return <div className={color}></div>;
      },
    },
    {
      title: '开工日期',
      dataIndex: 'kickoffDate',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '开工日期',
      dataIndex: 'kickoffDate',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '采购订单时间',
      align: 'center',
      sorter: true,
      dataIndex: 'purchaseTime',
      search: false,
    },
    {
      title: '采购订单时间',
      dataIndex: 'purchaseTime',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '计划到货日期',
      dataIndex: 'deliveryDate',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '计划到货日期',
      dataIndex: 'deliveryDate',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '实际到货日期',
      dataIndex: 'purchaseEndDate',
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '实际到货日期',
      dataIndex: 'purchaseEndDate',
      valueType: 'dateRange',
      align: 'center',
      sorter: true,

      hideInTable: true,
    },
    {
      title: '发货日期',
      dataIndex: 'sendDate',
      valueType: 'dateRange',
      hideInTable: true,
    },
    {
      title: '采购员',
      align: 'center',
      sorter: true,
      dataIndex: 'purchaser',

      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '唯一标识',
    //   dataIndex: 'identification',
    //  align: 'center',sorter: true,
    // },
    {
      title: '审核标志',
      dataIndex: 'isAudit',
      align: 'center',
      sorter: true,

      render: (text) => {
        return <div>{text == 'Y' ? '是' : text == 'N' ? '否' : '-'}</div>;
      },
      search: false,
      hideInTable: true, //隐藏审核标志
      // valueType: 'select',
      // request: async () => [
      //   { label: '是', value: 'Y' },
      //   { label: '否', value: 'N' },
      // ],
    },
    {
      title: '是否全部到货',
      dataIndex: 'isClosed',
      align: 'center',
      sorter: true,

      width: 120,
      render: (text) => {
        return <div>{text == 'Y' ? '是' : text == 'N' ? '否' : '-'}</div>;
      },
      search: false,
      // valueType: 'select',
      // request: async () => [
      //   { label: '是', value: 'Y' },
      //   { label: '否', value: 'N' },
      // ],
    },
    {
      title: '订单状态',
      align: 'center',
      sorter: true,
      dataIndex: 'poState',

      render: (text, record, _, action) => {
        return <div>{record.state == 0 ? '正常' : '短缺'}</div>;
      },
    },
    {
      title: '备注',
      dataIndex: 'memo',
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    /*     {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
     align: 'center',sorter: true, 
      width: 80,
      render: (text, record, _, action) => [
        <a
          key="lookForKey"
          onClick={() => {
            setPurchaseOrderId(record.id);
            setDetailVisit(true);
          }}
        >
          查看
        </a>,
         <a
           key="add"
           onClick={() => {
             setModalVisit(true);
             setPoIdentification(record.id);
           }}
         >
           新增物料
         </a>,
      ],
    }, */
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        let tempParams = form.getFieldsValue();
        tempParams = { ...tempParams, poIdentification: poIdentification };
        const result = await addPurchaseOrderDetail(tempParams);
        if (result != null) {
          message.success('添加成功');
        }
        setConfirmLoading(false);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch((err) => {
        setConfirmLoading(false);
      });
  };

  if (props.isShort) {
    return (
      <>
        <ProTable
          headerTitle="采购订单查询"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          formRef={ref}
          search={{
            labelWidth: 100,
            defaultCollapsed: true,
            ...tableSearchPublicConfig,
          }}
          toolBarRender={(action, { selectedRows }) => [
            <div className="projectScheduleGroup">
              <span>三天内：</span>
              <img src="../red.png" />
              <span>三天至七天：</span>
              <img src="../zt.gif"></img>
              <span>七天以上：</span>
              <img src="../zxz.gif"></img>
            </div>,
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                const filters = filterTranNew(ref.current.getFieldsValue());
                exportPurchaseOrder({
                  current: 1,
                  pageSize: 5000,
                  filters: filters,
                }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `PurchaseOrder.xls`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              导出
            </Button>,
          ]}
          request={async (params = {}, sort, filter) => {
            let sorters = sortTran(sort);
            let filters;
            if (props && props?.isShort) {
              filters = filterTranNew({
                ...params,
                isShort: 1,
              });
              filters = filterTranNew(params);
            } else {
              sorters = sortTran(sort);
              filters = filterTranNew(params);
            }
            /*           const result = await getPurchaseOrderByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          }); */
            const result = await getPurchaseOrderTotalByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            });
            console.log(result.data.content);
            result.data.content.map((item: any) => {
              item.createTime = item.createTime.split(' ')[0]; //处理日期，只保留到日
            });
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          scroll={{ x: 2200, y: 350 }}
          rowSelection={{}}
        />

        <Modal
          title={formTitle}
          width={800}
          open={modalVisit}
          onOk={handleSubmit}
          onCancel={() => setModalVisit(false)}
        >
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="left"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
            validateTrigger={['onBlur', 'onChange']}
          >
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item label="id" name="id" hidden={true}>
                  <Input />
                </Form.Item>
                <Form.Item
                  label="品牌"
                  name="brand"
                  //rules={[{ required: true, message: '请输入品牌信息！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="材料编号"
                  name="materialCode"
                  //rules={[{ required: true, message: '请输入材料编号！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="材料描述"
                  name="materialDesc"
                  // rules={[{ required: true, message: '请输入材料描述！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="材料数量"
                  name="materialQty"
                  rules={[
                    { required: true, message: '请输入材料数量！' },
                    {
                      pattern: /^\d{1,}$/,
                      message: '材料数量格式不对',
                      validateTrigger: ['onBlur', 'onChange'],
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="材料类型"
                  name="materialType"
                  //rules={[{ required: true, message: '请输入材料类型！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="未交货数量"
                  name="undeliveredQty"
                  rules={[
                    { required: true, message: '请输入未交货数量！' },
                    {
                      pattern: /^\d{1,}$/,
                      message: '未交货数量格式不对',
                      validateTrigger: ['onBlur', 'onChange'],
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="物料规格"
                  name="materialSpec"
                  // rules={[{ required: true, message: '请输入材料类型！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal
          title="物料详情"
          width={1200}
          open={detailVisit}
          onOk={() => setDetailVisit(false)}
          onCancel={() => setDetailVisit(false)}
        >
          <PurchaseOrderDetail purchaseOrderId={purchaseOrderId} ref={detailRef} />
        </Modal>
      </>
    );
  } else {
    return (
      <PageHeaderWrapper title={false} breadcrumb={undefined}>
        <ProTable
          headerTitle="采购订单查询"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          formRef={ref}
          search={{
            labelWidth: 100,
            defaultCollapsed: true,
            ...tableSearchPublicConfig,
          }}
          toolBarRender={(action, { selectedRows }) => [
            <div className="projectScheduleGroup">
              <span>三天内：</span>
              <img src="../red.png" />
              <span>三天至七天：</span>
              <img src="../zt.gif"></img>
              <span>七天以上：</span>
              <img src="../zxz.gif"></img>
            </div>,
            <Button
              key="button"
              icon={<RedoOutlined />}
              type="primary"
              onClick={async() => await purchaseOrderInfoSync()}
            >
              采购同步
            </Button>,
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                const filters = filterTranNew(ref.current.getFieldsValue());
                exportPurchaseOrder({
                  current: 1,
                  pageSize: 5000,
                  filters: filters,
                }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `PurchaseOrder.xls`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              导出
            </Button>,
          ]}
          request={async (params = {}, sort, filter) => {
            let sorters = sortTran(sort);
            let filters;
            if (props && props?.isShort) {
              filters = filterTranNew({
                ...params,
                isShort: 1,
              });
              filters = filterTranNew(params);
            } else {
              sorters = sortTran(sort);
              filters = filterTranNew(params);
            }
            /*           const result = await getPurchaseOrderByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            }); */
            const result = await getPurchaseOrderTotalByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            });
            console.log(result.data.content);
            result.data.content.map((item: any) => {
              item.createTime = item.createTime.split(' ')[0]; //处理日期，只保留到日
            });
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          scroll={{ x: 2200, y: 350 }}
          rowSelection={{}}
        />

        <Modal
          title={formTitle}
          width={800}
          open={modalVisit}
          onOk={handleSubmit}
          onCancel={() => setModalVisit(false)}
        >
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="left"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
            validateTrigger={['onBlur', 'onChange']}
          >
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item label="id" name="id" hidden={true}>
                  <Input />
                </Form.Item>
                <Form.Item
                  label="品牌"
                  name="brand"
                  //rules={[{ required: true, message: '请输入品牌信息！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="材料编号"
                  name="materialCode"
                  //rules={[{ required: true, message: '请输入材料编号！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="材料描述"
                  name="materialDesc"
                  // rules={[{ required: true, message: '请输入材料描述！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="材料数量"
                  name="materialQty"
                  rules={[
                    { required: true, message: '请输入材料数量！' },
                    {
                      pattern: /^\d{1,}$/,
                      message: '材料数量格式不对',
                      validateTrigger: ['onBlur', 'onChange'],
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="材料类型"
                  name="materialType"
                  //rules={[{ required: true, message: '请输入材料类型！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="未交货数量"
                  name="undeliveredQty"
                  rules={[
                    { required: true, message: '请输入未交货数量！' },
                    {
                      pattern: /^\d{1,}$/,
                      message: '未交货数量格式不对',
                      validateTrigger: ['onBlur', 'onChange'],
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="物料规格"
                  name="materialSpec"
                  // rules={[{ required: true, message: '请输入材料类型！' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal
          title="物料详情"
          width={1200}
          open={detailVisit}
          onOk={() => setDetailVisit(false)}
          onCancel={() => setDetailVisit(false)}
        >
          <PurchaseOrderDetail purchaseOrderId={purchaseOrderId} ref={detailRef} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
};
export default PurchaseOrder;
